global.Menstruation = db.collection("Menstruation.Menstruation");
// Start开始时间
// End结束日期
// Cycle周期
// Interval间隔
module.exports = {
	get: function(req, res) {
		var Mens = {};
		co(function*() {
			var mens = yield Menstruation.find({}).skip(((yield Menstruation.count()) || 1) - 1).limit(1).toArray();
			if (!mens.length) {
				Mens = {
					Start: "no data",
					End: "no data",
					Cycle: "no data",
					Interval: "no data"
				};
			} else {
				Mens = mens[0];
				Mens.End = mens[0].End || "no data";
				Mens.Cycle = mens[0].Cycle || "no data";
				Mens.Interval = mens[0].Interval || "0";
			};
			console.log(Mens)
			res.send(Mens);
		}).catch(e => {
			res.send({});
			console.log(e);
		});
	},
	post: function(req, res) {
		var Mens = req.body;
		co(function*() {
			var mensCount = yield Menstruation.count();
			if (mensCount > 0) {
				var doc = yield Menstruation.find({}).skip(mensCount - 1).limit(1).toArray();
				doc = doc[0];
				Mens.Interval = parseInt((Mens.Start - doc.Start) / 1000 / 60 / 60 / 24) ;
				Menstruation.insertOne(Mens);
			} else {
				Mens.Interval = 0;
				Menstruation.insertOne(Mens);
			}
			res.send({})
		}).catch(e => {
			res.send({});
			console.log("post");
			console.log(e);
		});
	},
	put: function(req, res) {
		var Mens = req.body;
		co(function*() {
			var mensCount = yield Menstruation.count();
			var doc = yield Menstruation.find({}).skip(mensCount - 1).limit(1).toArray();
			doc = doc[0];
			Mens.Cycle = parseInt((Mens.End - doc.Start) / 1000 / 60 / 60 / 24) + 1;
			var r = yield Menstruation.updateOne({
				_id: doc._id
			}, {
				$set: Mens
			}, {
				upsert: true
			});
			console.log(Mens);
			res.send({});
		}).catch(e => {
			console.log(e);
			res.send({});
		});
	},
	delete: function(req, res) {

	}
};
// public function
function _numToChinese(num) {
	if (num == 1) {
		return '一';
	};
	if (num == 2) {
		return '二';
	};
	if (num == 3) {
		return '三';
	};
	if (num == 4) {
		return '四';
	};
	if (num == 5) {
		return '五';
	};
	if (num == 6) {
		return '六';
	};
	if (num == 7) {
		return '日';
	};
};